//引入axios
import axios from 'axios'
import {Loading,MessageBox} from 'element-ui';
import 'muse-ui-progress/dist/muse-ui-progress.css';
import  NProgress  from 'muse-ui-progress';
import Toast from 'muse-ui-toast';
import comm from '../uilt/CommunicationEncryption'
let cancel, promiseArr = {};
let loading = '';
const CancelToken = axios.CancelToken;
//请求拦截器
axios.interceptors.request.use(config => {
	//发起请求时，取消掉当前正在进行的相同请求
	if (promiseArr[config.url]) {
		promiseArr[config.url]('操作取消')
		promiseArr[config.url] = cancel
	} else {
		promiseArr[config.url] = cancel
	}
	return config
}, error => {
	return Promise.reject(error)
})

axios.interceptors.response.use(response => {
//响应拦截器即异常处理
	//loading.close();
	NProgress.done();
	switch (response.status) {
		case 200:
			if (Object.prototype.toString.call(response.data) != '[object Object]') {
				response.data = JSON.parse(response.data)
			}
			if (response.data.code == 200) {
				return Promise.resolve(response.data)
			} else {
				Toast.error(response.data.msg);
				// MessageBox.confirm(response.data.msg, '提示', {
				// 	confirmButtonText: '确定',
				// 	 cancelButtonText: '取消',
				// 	type: 'error'
				// });
				return Promise.resolve(response.data)
			}
			break;
		default:
			Toast.error('请求错误，请检查网络');
			// MessageBox.confirm('请求错误，请检查网络（' + response.statusText + '）', '提示', {
			// 	confirmButtonText: '确定',
			// 	 cancelButtonText: '取消',
			// 	type: 'error'
			// });
			return Promise.resolve(response.data)
	}
});


//axios.defaults.baseURL = ;

axios.defaults.headers = {
	'X-Requested-With': 'XMLHttpRequest_3b4604bb=b855d124-aab9-441a-8c3e-5cdd941c3a1a'
}
axios.defaults.timeout = 10000;

export default {
	get(url, param) {
		param.t = Date.parse(new Date());
		NProgress.start();

		return new Promise((resolve, reject) => {
			axios({
				headers:comm.headers(),
				method: 'get',
				url:(process.env.VUE_APP_URL?process.env.VUE_APP_URL:'')+url,
				params: param,
				cancelToken: new CancelToken(c => {
					cancel = c
				})
			}).then(res => {
				if (Object.prototype.toString.call(res) != '[object Object]') {
					res = JSON.parse(res)
				}
				// loading.close();
				NProgress.done();
				resolve(res)
			}).catch((error)=>{
				//console.log(error);
				Toast.error('请求错误，请检查网络');
		    })
		})
	},
	//post请求
	post(url, param) {
		param.t = Date.parse(new Date());
		NProgress.start();
		return new Promise((resolve, reject) => {
			axios({
				headers:comm.headers(),
				method: 'post',
				url:(process.env.VUE_APP_URL?process.env.VUE_APP_URL:'')+url,
				data: param,
				cancelToken: new CancelToken(c => {
					cancel = c
				})
			}).then(res => {
				if (Object.prototype.toString.call(res) != '[object Object]') {
					res = JSON.parse(res)
				}
				NProgress.done();
				resolve(res)
			}).catch((error)=>{
				Toast.error('请求错误，请检查网络');
			})
		})
	}
}
